package com.touna.annotation.hibernateValidator;

import com.touna.annotation.entity.Customer;
import com.touna.annotation.facet.First;
import com.touna.annotation.facet.GroupOrder;
import com.touna.annotation.facet.Three;
import com.touna.annotation.facet.Two;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * author: xl
 * time: 2018/6/15 14:59
 * description:
 **/
public class ValidatorTest {


   public static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();


    /**
     * 功能描述: <br>
     * 〈注解验证参数〉
     *
     * @param obj
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static <T> String validate(T obj) {
        String msg = "";
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        // 抛出检验异常
        if (constraintViolations.size() > 0) {
            msg =constraintViolations.iterator().next().getMessage();
        }
        return msg;
    }


    /**
     * 分组校验
     * 不同的业务有不同的参数校验组合
     * @param obj
     * @param groups
     * @param <T>
     */
    public static <T> String validate(T obj,Class ... groups) {
        String msg = "";
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        // 抛出检验异常
        if (constraintViolations.size() > 0) {
            msg =constraintViolations.iterator().next().getMessage();
        }
        return msg;
    }


    public static void main(String[] args) {
        Customer customer = new Customer();
        customer.setName("xl");
        customer.setAge(11);
        customer.setMobile("1581649786");
//        validate(customer);

//        String validMessage = validate(customer, First.class,Two.class, Three.class);
//        System.out.println(validMessage);
//        String validateGroupMsg = validate(customer, GroupOrder.class);
//        System.out.println(validateGroupMsg);

//        customer.setIdcard("4311122145845");
        String validIdcard = validate(customer);
        System.out.println(validIdcard);

    }

}
